<template>
  <el-scrollbar class="design-scrollbar" ref="scrollbarRef">
    <div
      id="smartDesign"
      :class="griddlingClassName"
      @dragover.prevent
      @drop="handleDrop"
      @click="dialogVisible = false"
      :style="{
        zoom: scale,
        width: `${pageData.resolutionRatio[0] ?? 1920}px`,
        height: `${pageData.resolutionRatio[1] ?? 1080}px`,
        backgroundSize: `${pageData.griddling ?? 16}px ${pageData.griddling ?? 16}px`,
      }"
    >
      <DraggableContainer
        :adsorbCols="adsorbCols"
        :adsorbRows="adsorbRows"
        :referenceLineVisible="true"
        :referenceLineColor="pageData.griddlingColor"
        :style="{
          width: `${pageData.resolutionRatio[0] ?? 1920}px`,
          height: `${pageData.resolutionRatio[1] ?? 1080}px`,
        }"
      >
        <Vue3DraggableResizable
          :style="{ zIndex: item.z }"
          v-for="item in layoutList"
          :key="item.id"
          :initW="item.w"
          :initH="item.h"
          v-model:x="item.x"
          v-model:y="item.y"
          v-model:w="item.w"
          v-model:h="item.h"
          v-model:active="item.active"
          :draggable="true"
          :resizable="true"
          :classNameActive="item.config?.className"
          :classNameDraggable="item.config?.className"
          :classNameHandle="item.config?.className"
          @dragging="handleDragStart"
          @resizing="handleResize"
          @drag-end="handleDragStart"
          @resize-end="handleResize"
          @click.right="handlePopover(item)"
        >
          <div
            class="drab-list"
            :style="{ background: item.style?.background }"
          >
            <component
              :formData="item"
              :is="previewComponents[item.config?.key]"
            ></component>
          </div>
        </Vue3DraggableResizable>
      </DraggableContainer>
      <div class="popover" v-show="dialogVisible" :style="popoverStyle">
        <div class="popover-list" @click="handleOperate(1)">置顶</div>
        <div class="popover-list" @click="handleOperate(2)">上一层</div>
        <div class="popover-list" @click="handleOperate(3)">下一层</div>
        <div class="popover-list" @click="handleOperate(4)">置底</div>
        <div class="popover-list danger" @click="handleOperate(5)">删除</div>
      </div>
    </div>
  </el-scrollbar>
</template>
<script setup>
import { nextTick, toRefs, watch } from 'vue'
import { getUUID, loadComponents } from '../utils/index'
import { initLayoutData } from '../config/layoutType'
import useDesignStore from '@/store/modules/baseDesign'
const props = defineProps({
  property: {
    type: Object,
    default: () => {},
  },
  scale: {
    type: Number,
    default: 1,
  },
  globalConfig: {
    type: Object,
    default: () => {},
  },
})
let scrollbarRef = ref()
let popoverStyle = ref({
  top: 0,
  left: 0,
})
let dialogVisible = ref(false)
let adsorbCols = ref()
let adsorbRows = ref()
let { property, scale, globalConfig } = toRefs(props)
let layoutList = ref([])
let pageData = ref({})
let griddlingClassName = ref(['design'])
let previewComponents = loadComponents('preview')
let selectLayout = ref({})
const emits = defineEmits(['resize'])
watch(
  () => property.value,
  (newVal) => {
    if (newVal) {
      let { id } = newVal
      let selectData = getLayout('id', id)
      if (selectData && selectData.length) {
        selectData[0] = newVal
      }
    }
  },
  {
    deep: true,
  },
)
watch(
  () => layoutList.value,
  (arr) => {
    if (arr) {
      if (arr && arr.length) {
        for (let i = 0; i < arr.length; i++) {
          // 删除图层
          if (arr[i].delete) {
            arr.splice(i, 1)
            i--
          } else {
            arr[i].z = i
          }
        }
        useDesignStore().setLayoutList(arr ?? [])
      }
    }
  },
  {
    deep: true,
  },
)
watch(
  () => globalConfig.value,
  (newVal) => {
    if (newVal) {
      pageData.value = newVal
      adsorbCols.value = generateGrid(
        newVal.resolutionRatio[0],
        newVal.griddling,
      )
      adsorbRows.value = generateGrid(
        newVal.resolutionRatio[1],
        newVal.griddling,
      )
      let classList = []
      griddlingClassName.value = ['design']
      if (
        newVal.resolutionRatio[0] % newVal.griddling >=
        newVal.griddling / 2
      ) {
        classList.push('griddling-border-right')
      }
      if (
        newVal.resolutionRatio[1] % newVal.griddling >=
        newVal.griddling / 2
      ) {
        classList.push('griddling-border-bottom')
      }
      griddlingClassName.value.push(...classList)
    }
  },
  {
    deep: true,
    immediate: true,
  },
)
// 拖拽开始-中-结束
let handleDragStart = (res) => {
  let activeDrab = getLayout('active', true)
  emits('resize', Object.assign(activeDrab, res))
}
let handleResize = (res) => {
  let activeDrab = getLayout('active', true)
  emits('resize', Object.assign(activeDrab, res))
}
// 拖拽
let handleDrop = (event) => {
  let { layerX: x, layerY: y } = event
  let data = event.dataTransfer.getData('subassemblyData')
  try {
    let subassemblyData = JSON.parse(data)
    let width = x - initLayoutData.asideW
    let height = y - initLayoutData.navH
    subassemblyData.x = width
    subassemblyData.y = height
    subassemblyData.z = Number(subassemblyData.z) + layoutList.value.length
    subassemblyData.id = getUUID()
    subassemblyData.name = subassemblyData.name + getNameIndex(subassemblyData)
    nextTick(() => {
      layoutList.value.push(subassemblyData)
      emits('resize', subassemblyData)
    })
  } catch (err) {
    console.error(err)
  }
}

function getNameIndex(data) {
  return layoutList.value.filter((item) => item.type === data.type).length + 1
}
function getLayout(field, type) {
  return layoutList.value.filter((item) => item[field] == type)[0]
}
function generateGrid(total, step) {
  let result = []
  for (let i = 0; i <= total; i += step) {
    result.push(i)
  }
  return result
}
let handlePopover = (res) => {
  let { x, y, w, h } = res
  popoverStyle.value = {
    left: `${x + w / 2}px`,
    top: `${y + h / 2}px`,
  }
  selectLayout.value = getLayout('active', true)
  dialogVisible.value = true
}
let handleOperate = (item) => {
  switch (item) {
    case 1:
      // 置顶
      selectLayout.value.z = -1
      sortLayout()
      break
    case 2:
      // 上一层
      selectLayout.value.z = selectLayout.value.z + 1.5
      sortLayout()
      break
    case 3:
      // 下一层
      selectLayout.value.z = selectLayout.value.z - 1.5
      sortLayout()
      break
    case 4:
      // 置底
      selectLayout.value.z = layoutList.value.length + 1
      sortLayout()
      break
    case 5:
      // 删除图层
      selectLayout.value.delete = true
      break
  }
  dialogVisible.value = false
}
function sortLayout() {
  layoutList.value.sort((a, b) => {
    return b.z - a.z
  })
}
</script>
<style scoped lang="scss">
$suffixes: tl, tm, tr, mr, ml, bl, bm, br;
.design-scrollbar {
  height: calc(100vh - 60px);
  width: calc(100vw - 316px);
  padding: 16px;
  box-sizing: border-box;
}
.design {
  position: relative;
  background-image: linear-gradient(
      rgba(216, 216, 221, 0.7) 0px,
      transparent 0px
    ),
    linear-gradient(90deg, rgba(216, 216, 221, 0.4) 1px, transparent 0px),
    linear-gradient(rgba(216, 216, 221, 0.7) 1px, transparent 0px),
    linear-gradient(90deg, rgba(216, 216, 221, 0.4) 1px, transparent 0px);
}
.griddling-border-right {
  border-right: 1px solid rgba(216, 216, 221, 0.4);
}
.griddling-border-bottom {
  border-bottom: 1px solid rgba(216, 216, 221, 0.4);
}
.drab-list {
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  cursor: move;
}

:deep(.image-active) {
  border: none;
  @each $suffix in $suffixes {
    .image-active-#{$suffix} {
      background-color: #4af;
      border-radius: 50%;
      width: 8px;
      height: 8px;
    }
  }
}
:deep(.video-active) {
  border: none;
  @each $suffix in $suffixes {
    .video-active-#{$suffix} {
      background-color: #43c706;
      border-radius: 50%;
      width: 8px;
      height: 8px;
    }
  }
}
:deep(.text-active) {
  border: none;
  @each $suffix in $suffixes {
    .text-active-#{$suffix} {
      background-color: #dd8005;
      border-radius: 50%;
      width: 8px;
      height: 8px;
    }
  }
}

:deep(.time-active) {
  border: none;
  @each $suffix in $suffixes {
    .time-active-#{$suffix} {
      background-color: #7be2cc;
      border-radius: 50%;
      width: 8px;
      height: 8px;
    }
  }
}
.popover {
  position: absolute;
  z-index: 2000;
  top: 0;
  left: 0;
  background: #fff;
  box-shadow: 0px 0px 12px rgba(0, 0, 0, 0.12);
  width: 160px;
  border-radius: 6px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}
.popover-list {
  cursor: pointer;
  width: 100%;
  text-align: center;
  padding: 16px;
  box-sizing: border-box;
}
.danger {
  color: #f56c6c;
}
.popover-list:hover {
  background: #e6e8eb;
}
.popover-list:nth-last-child(1) {
  border: none;
}
</style>
